package com.rslai.commons.validator.jsonvalidator.validators;

import com.rslai.commons.validator.jsonvalidator.schema.Schema;

/**
 * JSON校验器接口
 */
public abstract class Validator {
    private Validator nextValidator;
    private String currentKeyPath;
    private Schema<Object> valueSchema;

    /**
     * 校验JSON对象
     * @param object 待验证的JSON对象
     */
    public abstract void doValidate(Object object);

    /**
     * 返回是否执行下一个校验
     * @return
     */
    protected boolean hasExecuteNextValidator(){
        return true;
    }

    /**
     * 校验
     * @param object object
     */
    public void validate(Object object) {
        if (valueSchema != null && valueSchema.isNecessaryCheck()) {
            doValidate(object);
            if (hasExecuteNextValidator() && hasNextValidator()) {
                getNextValidator().validate(object);
            }
        }
    }

    /**
     * 是否有下一个校验
     * @return
     */
    private boolean hasNextValidator() {
        return getNextValidator() != null;
    }

    /**
     * 返回校验名称
      * @return 校验名称
     */
    public abstract String name();

    /**
     * 返回下一个校验
     * @return Validator
     */
    public Validator getNextValidator() {
        return nextValidator;
    }

    /**
     * 设置下一个校验
     * @param nextValidator Validator
     */
    public void setNextValidator(Validator nextValidator) {
        this.nextValidator = nextValidator;
    }

    /**
     * 返回当前key路径
     * @return key路径
     */
    public String getCurrentKeyPath() {
        return currentKeyPath;
    }

    /**
     * 设置当前kye路径
     * @param currentKeyPath key路径
     */
    public void setCurrentKeyPath(String currentKeyPath) {
        this.currentKeyPath = currentKeyPath;
    }

    /**
     * 返回object字符串
     * @param object object
     * @return object字符串
     */
    protected String getString(Object object) {
        return object == null ? null : object.toString();
    }

    /**
     * 返回校验规则
     * @return schema
     */
    public Schema<?> getValueSchema() {
        return valueSchema;
    }

    /**
     * 设置校验规则
     * @param valueSchema schema
     */
    public void setValueSchema(Schema<?> valueSchema) {
        this.valueSchema = (Schema<Object>)valueSchema;
    }

    /**
     * 判断是否是必要检查项
     * @return boolean boolean
     */
    public boolean isNecessaryCheck() {
        return valueSchema != null && valueSchema.isNecessaryCheck();
    }
}
